package model

import (
	"bufio"
	"fmt"
	"goland-study/go_code/basis/chapter09-file/constant"
	"io"
	"os"
)

type CharNum struct {
	NumCount   int
	CharCount  int
	SpaceCount int
	OtherCount int
}

var count CharNum

func FileCharNum() {
	open, err := os.Open(constant.FILENAME)
	if err != nil {
		return
	}
	defer func(open *os.File) {
		err2 := open.Close()
		if err2 != nil {
			fmt.Println("关闭资源失败")
		}
	}(open)

	reader := bufio.NewReader(open)
	for true {
		readString, err := reader.ReadString('\n')
		if err == io.EOF {
			fmt.Println("末尾了")
			break
		}
		//统计字符出现的次数
		Count([]rune(readString))
	}

	fmt.Println(count)
}

func (c CharNum) String() string {
	return fmt.Sprintf("NumCount=[%v]，CharCount=[%v]，SpaceCount=[%v]，OtherCount=[%v]", c.NumCount, c.CharCount, c.SpaceCount, c.OtherCount)
}

func Count(str []rune) {
	for _, r := range str {
		switch {
		case r > 'a' && r < 'z':
			fallthrough
		case r > 'A' && r < 'Z':
			count.CharCount++
		case r > '0' && r < '9':
			count.NumCount++
		case r == ' ' || r == '\t':
			count.SpaceCount++
		default:
			count.OtherCount++
		}
	}
}
